package com.hansen.library.ui.widget.listview;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.ListView;

/**
 * 高度固定
 *
 * @author han
 * @date 2019/9/21
 */
public class FixedHeightListView extends ListView {
    public FixedHeightListView(Context context) {
        super(context);
    }

    public FixedHeightListView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public FixedHeightListView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public void setListViewHeightBasedOnChildren(int itemCount) {
        ListAdapter listAdapter = getAdapter();

        if (listAdapter == null || listAdapter.getCount() < itemCount) {
            return;
        }

        int totalHeight = 0;

        for (int i = 0; i < itemCount; i++) {
            View listItem = listAdapter.getView(i, null, this);

            listItem.measure(0, 0);

            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = this.getLayoutParams();

        params.height = totalHeight + (this.getDividerHeight() * (itemCount - 1));

        this.setLayoutParams(params);
    }
}
